demo1:
var MongoClient = require('mongodb').MongoClient;
var count = 0;
var promise1 = new Promise(function(resolve, reject) {
MongoClient.connect('mongodb://localhost:27017/zuckjet', function(err, db) {
if (db) {
var collection = db.collection('users');
collection.find({}).toArray(function(err, docs) {
resolve(docs);
});
}
if (err) {
reject(err);
}
});
});
promise1.then(function(data) {
setTimeout(function() {
console.log(++count);
}, 5000);
}).then(function(res) {
console.log('second function begin to print');
console.log(count);
})
上述代码输出结果为:
second function begin to print
0
1 //大概5秒后输出
dem02:
var MongoClient = require('mongodb').MongoClient;
var count = 0;
var promise1 = new Promise(function(resolve, reject) {
MongoClient.connect('mongodb://localhost:27017/zuckjet', function(err, db) {
if (db) {
var collection = db.collection('users');
collection.find({}).toArray(function(err, docs) {
resolve(docs);
});
}
if (err) {
reject(err);
}
});
});
promise1.then(function(data) {
new Promise(function(resolve, reject) {
setTimeout(function() {
console.log(++count);
resolve(count);
}, 5000);
});
}).then(function(res) {
console.log('second function begin to print');
console.log(res);
console.log(count);
})
上述代码输出如下:
second function begin to print
undefined
0
1 //大约5秒后输出
demo3:
var MongoClient = require('mongodb').MongoClient;
var count = 0;
var promise1 = new Promise(function(resolve, reject) {
MongoClient.connect('mongodb://localhost:27017/zuckjet', function(err, db) {
if (db) {
var collection = db.collection('users');
collection.find({}).toArray(function(err, docs) {
resolve(docs);
});
}
if (err) {
reject(err);
}
});
});
promise1.then(function(data) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log(++count);
resolve(count);
}, 5000);
});
}).then(function(res) {
console.log('second function begin to print');
console.log(res);
console.log(count);
})
上述代码输出结果如下:
1 //大约五秒输出
second function begin to print
1
1
总结如下:
在形如:promise.then(...语句1...).then(...语句2...)中,
语句1中如果不使用return语句,语句2中无法接收到语句1中的参数
语句1中如果返回的是promise,语句2会等待语句1的resolve参数传递过来
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。